﻿
using System;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Windows.Forms;

namespace n_Email
{
	//邮件发送器
	public static class Email
	{
		//发送纯文本邮件
		public static bool SendMailSelf( string mailService, string mailAddr, string passCode, string Label, string Text )
		{
			return SendMailSelf( mailService, mailAddr, passCode, Label, Text, null );
		}
		
		//发送带有附件的邮件
		public static bool SendMailSelf( string mailService, string mailAddr, string passCode, string Label, string Text, string atPath )
		{
			MailMessage message = null;
			
			try {
				string emailAcount = ConfigurationManager.AppSettings["EmailAcount"];
				string emailPassword = ConfigurationManager.AppSettings["EmailPassword"];
				string reciver = mailAddr;
				string content = Text;
				
				message = new MailMessage();
				
				//设置发件人,发件人需要与设置的邮件发送服务器的邮箱一致
				MailAddress fromAddr = new MailAddress( mailAddr );
				message.From = fromAddr;
				
				//设置收件人,可添加多个,添加方法与下面的一样
				message.To.Add(reciver);
				
				//设置邮件标题
				message.Subject = Label;
				
				//设置邮件内容
				message.Body = content;
				
				//添加附件
				if( atPath != null ) {
					
					string[] cut = atPath.Split( '\n' );
					foreach( string apath in cut ) {
						message.Attachments.Add( new Attachment( apath ) );
					}
				}
				
				//设置邮件发送服务器,服务器根据你使用的邮箱而不同,可以到相应的 邮箱管理后台查看,下面是QQ的
				SmtpClient client = new SmtpClient( mailService, 25 );
				
				//设置发送人的邮箱账号和密码
				client.Credentials = new NetworkCredential( mailAddr, passCode );
				
				//启用ssl,也就是安全发送
				client.EnableSsl = true;
				
				//发送邮件
				client.Send(message);
			}
			catch ( Exception e ) {
				MessageBox.Show( e.ToString(), "出错信息" );
				return false;
			}
			try {
				message.Attachments.Dispose();
			}
			catch {}
			try {
				message.Dispose();
			}
			catch {}
			return true;
		}
	}
}


